package com.ktg.service.impl;

import com.ktg.ktgcommon.domain.user.SysRole;
import com.ktg.ktgcommon.domain.user.SysUser;
import com.ktg.ktgcommon.domain.user.TPremission;
import com.ktg.mapper.PremissionMapper;
import com.ktg.mapper.RoleMapper;
import com.ktg.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private PremissionMapper premissionMapper;
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser tUser = userMapper.selectByLoginAct(username);
        if (tUser == null) {
            throw new UsernameNotFoundException("登录账号不存在");
        }
        //查询一下当前用户的角色
        List<SysRole> tRoleList = roleMapper.selectByUserId(tUser.getUserId());
        //字符串的角色列表
        List<String> stringRoleList = new ArrayList<>();
        tRoleList.forEach(tRole -> {
            stringRoleList.add(tRole.getRoleName());
        });
        List<TPremission> tPermissionList = premissionMapper.getPremissionList(tUser.getRoleId());
        List<String> stringPermissionList = tPermissionList.stream()
                .map(TPremission::getCode)
                .collect(Collectors.toList());
        System.out.println(stringPermissionList);
        // 设置用户的权限
        tUser.setPremissionList(stringPermissionList);
        tUser.setRoleList(stringRoleList); //设置用户的角色
        return tUser;
    }
}
